# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time


from utils.alerts.doris_telnet_check import net_is_used
from utils.operators.rich_sql_sensor import RichSqlSensor

label = f"dwd_center_store_new_detail_{int(time())}"
timeout = timedelta(minutes=10).seconds

# from airflow.operators.dummy_operator import DummyOperator
# doris_jms_dwd__dwd_center_store_new_detail = DummyOperator(
#     task_id='doris_jms_dwd__dwd_center_store_new_detail',
#     email='chenhongping@yl-scm.com',
#     retries=0,
#     priority_weight=0,
#     # sla=timedelta(hours=2),
# )
dorisConn = net_is_used()
doris_jms_dwd__dwd_center_store_new_detail = RichSqlSensor(
    task_id='doris_jms_dwd__dwd_center_store_new_detail',
    email=['lukunming@jtexpress.com','yl_bigdata@yl-scm.com'],
    pool='broker_load_pool',
    conn_id='new_doris',
    pre_sql=f"""
             TRUNCATE TABLE jms_dwd.dwd_center_store_new_detail PARTITION (p{{{{ execution_date | date_add(-1) | cst_ds_nodash }}}});
             LOAD LABEL jms_dwd.{label} (
                 DATA INFILE("hdfs://yl-bg-hdp/dw/hive/jms_dm.db/external/dm_cn_export_center_store_new_detail_dt/dt={{{{ execution_date | date_add(-1) | cst_ds }}}}/*")
                 INTO TABLE dwd_center_store_new_detail
                      COLUMNS TERMINATED BY "\\x01"
                 FORMAT AS 'PARQUET'
                      (scan_date,center_subordinate_agent_name,center_subordinate_agent_code,inputsite,scansitecode,billcode,packagecode,transfercode,planned_arrival_time,actual_arrival_time,arrival_time,send_time,store_type,start_network_name,start_center_name,start_agent_name,end_network_name,end_center_name,end_agent_name)
             )
             WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
             PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dwd WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dwd WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )


